import React from 'react';
import classnames from 'classnames';
import { inject } from 'mobx-react';
import { WeaPopoverHrm, WeaErrorPage, WeaTools,WeaLocaleProvider } from 'ecCom';
import equals from 'deep-equal';
import _ from 'lodash';
import ElectricSign from './electricSign';
const getLabel = WeaLocaleProvider.getLabel;

export interface DevDockerProps {
    prefixCls?: string;
    className?: string;
    params?: any;
    location?: any;
    ElectricSign:any;
}

const getQuery = (href: string) => {
    const lastofnum = href.lastIndexOf('?');
         href = href.slice(lastofnum);
    const query = href.split('?')[1];
    const querys = query ? query.split("&") : [];
    const queryObj: any = {};
    querys.map(q => {
        const index = q.indexOf("=");
        const name = q.substring(0, index);
        const value = q.substring(index + 1);
        _.set(queryObj, name, value);
    });
    return queryObj;
}

@inject('ElectricSign')
export class DevDocker extends React.Component<DevDockerProps, any> {
    componentWillMount() {
        this.doUpdate(this.props);
    }
    componentDidMount() {
        if(window.location.href.indexOf('/spa/cube/index.html') > -1 || window.location.href.indexOf('/spa/cube/index.jsp') > -1){
            document.title = getLabel(16641, "高效源于协同");
        }
    }
    componentWillReceiveProps(nextProps) {
        let nextP = nextProps.location.action;
        let thisP = this.props.location;
        delete nextP.action;
        delete thisP.action;
        if (!equals(nextP, thisP)) {
            this.doUpdate(nextProps);
        }
    }
    doUpdate = (props) => {
        const { location, params, ElectricSign,} = props;
        const query = getQuery(decodeURI(location.search));
        const store = { elesign: ElectricSign }[params.guid];
        if (store && store.updateParams) {
            store.updateParams({ ...query, ...params, _key: location.key });
        }
    }
    render() {
        const { prefixCls = 'coms-mode-devdocker', className, params } = this.props;
        const Com = {
            elesign: ElectricSign,
        }[params.guid];
        const classNames = classnames(className, prefixCls, `coms-mode-${params.guid}`);
        const props = { location: this.props.location } as any;
        return (
            <div className={classNames}>
                {(window.location.href.indexOf('/spa/cube/index.html') > -1 || window.location.href.indexOf('/spa/cube/index.jsp') > -1)  && <WeaPopoverHrm /> }
                {Com && <Com {...props} />}
            </div>
        )
    }
}


const MyErrorHandler = () => {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
        <WeaErrorPage msg={hasErrorMsg ? this.props.error :  getLabel(383324, "对不起，该页面异常，请联系管理员")+"!"} />
    );
}
export default WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(DevDocker);
